package com.smbms.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.smbms.config.Authoritys;
import com.smbms.entity.SmbmsUser;
import com.smbms.entity.page.Page;
import com.smbms.entity.vo.SmbmsUserUpdateVo;
import com.smbms.service.RoleService;
import com.smbms.service.UserService;

/**
 * 用户管理控制器
 * @ClassName: UserController 
 * @Description: (这里用一句话描述这个类的作用) 
 * @author Lyrk.Guo
 * @date 2018年7月7日 下午5:22:27
 */
@Controller
@RequestMapping("/user")
public class UserController {//extends BaseController{

	@Autowired
	UserService userService;
	
	@Autowired
	RoleService roleService;
	
	@RequiresPermissions(Authoritys.USER_LIST)
	@RequestMapping("/list")
	public String select(Model model,
			String queryUserName,
			Integer queryUserRole,
			@RequestParam(value="pageNo",required = false, defaultValue = "1")Integer pageNo,
			@RequestParam(value="pageSize",required = false, defaultValue = "10")Integer pageSize){
		
		Page<SmbmsUser> pageInfo = userService.selectUserByPage(queryUserName,queryUserRole,pageNo,pageSize);
		
		model.addAttribute("queryUserName", queryUserName);
		model.addAttribute("queryUserRole", queryUserRole);
		model.addAttribute("roleList", roleService.selectAll());
		model.addAttribute("userList", pageInfo.getList());
		model.addAttribute("pageInfo", pageInfo);
		return "userlist";
	}

	@RequestMapping("/toAdd")
	public String toAddPage(Model model){
		
		model.addAttribute("roleList", roleService.selectAll());
		return "useradd";
	}


	@RequiresPermissions(Authoritys.USER_ADD)
	@RequestMapping("/add")
	public String add(
			@Valid SmbmsUser user,
			BindingResult bindingResult,//使用JSR 303验证，BindingResult必须在验证@Valid的后面
			Model model){
		
		//没有通过验证
		if(bindingResult.hasErrors()){
			model.addAttribute("errors", bindingResult.getAllErrors());
			return "useradd";
		}
		
		int n = userService.addUser(user);
		if(n>0){
			return "redirect:list";
		}
		model.addAttribute("msg", "添加失败");
		return "useradd";
	}

	@RequiresPermissions(Authoritys.USER_UPDATE)
	@RequestMapping("/update")
	public String update(
			@Valid SmbmsUserUpdateVo user,
			BindingResult bindingResult,//使用JSR 303验证，BindingResult必须在验证@Valid的后面
			Model model){
		
		//没有通过验证
		if(bindingResult.hasErrors()){
			model.addAttribute("errors", bindingResult.getAllErrors());
			return "usermodify";
		}
		
		int n = userService.updateUser(user);
		if(n>0){
			return "redirect:list";
		}
		model.addAttribute("msg", "修改失败");
		return "usermodify";
	}

	@RequiresPermissions(Authoritys.USER_GET)
	@RequestMapping("/get")
	public String get(Long id,Model model){
		SmbmsUser user = userService.getUserById(id);
		model.addAttribute("user", user);
		model.addAttribute("roleList", roleService.selectAll());
		return "usermodify";
	}
	
	/**
	 * REST风格
	 * @param id
	 * @param model
	 * @return
	 */
	@RequiresPermissions("user_view")
	@ResponseBody
	@RequestMapping(value = "/view/{id}")
	public SmbmsUser view(@PathVariable Long id,Model model){
		SmbmsUser user = userService.getUserById(id);
		//model.addAttribute("user", user);
		//model.addAttribute("roleList", roleService.selectAll());
		return user;//JSON.toJSONString(user);
	}
	
	@ResponseBody
	@RequestMapping("/checkUserCode")
	public String checkUserCode(String userCode){
		int n =  userService.checkUserCode(userCode);
		if(n>0){
			//已存在
			return "true";
		}
		return "false";
	}
	
	@RequestMapping("/login")
	public String login(String userCode,
			String userPassword,
			Model model,
			HttpSession session,
			HttpServletRequest request){
		
		
		Subject sub = SecurityUtils.getSubject();
        // 用户输入的账号和密码,,存到UsernamePasswordToken对象中..然后由shiro内部认证对比,
        // 认证执行者交由 com.battcn.config.AuthRealm 中 doGetAuthenticationInfo 处理
        // 当以上认证成功后会向下执行,认证失败会抛出异常
        UsernamePasswordToken token = new UsernamePasswordToken(userCode, userPassword);
        try {
            sub.login(token);

    		return "frame";
        }  catch (UnknownAccountException e) {
        	request.setAttribute("error", "用户名不存在");
            token.clear();
        }catch (IncorrectCredentialsException  ice) {
        	request.setAttribute("error", "用户名密码错误");
            token.clear();
		}catch (ExcessiveAttemptsException  eae) {
        	request.setAttribute("error", "用户登录失败次数过多，锁定十分钟");
            token.clear();
		}catch (LockedAccountException lae) {
        	request.setAttribute("error", "用户名被锁定");
            token.clear();
        } catch (AuthenticationException e) {
        	request.setAttribute("error", "用户验证未通过");
        }
        
		//失败
		return "login";
	}
	
	/**
	 * 局部异常处理
	 * 只针对当前的controller
	 * @return
	 */
//	@ExceptionHandler(value = RuntimeException.class)
//	public String exceptionResolve(){
//		return "error";
//	}
}
